<template>
  <el-select clearable
             placeholder="请选择"
             v-bind="attrs"
             style="width: 168px"
             allowClear>
    <el-option v-for="item in myOptions"
               :key="item.value"
               :label="item.label"
               :value="item.value" />
  </el-select>
</template>

<script lang="ts" setup>
import { post, get } from '@/server/request'
const emit = defineEmits(['update:value'])
const attrs = useAttrs()
const props = defineProps({
  value: [String, Number, Array],
  url: String,
  params: {
    type: Object,
    default: () => {
      return {}
    }
  },
  options: {
    type: Array,
    default: () => []
  },
  method: {
    type: String,
    default: 'post'
  },
  keyName: {
    type: Array,
    default: () => 'key'
  },
  valueName: {
    type: String,
    default: () => 'value'
  }
})

const AXIOS_METHOD = {
  post: post,
  get: get
}

const myOptions = ref(props.options)
let reqParams = toRaw(props.params)

const getServerUrl = () => {
  return `${import.meta.env.VITE_APP_CONFIG}/config/list-column`
}

const getOptions = async () => {
  if (props.options && props.options.length > 0) {
    return
  }
  const { success, data, retInfo } = await AXIOS_METHOD[
    props.method.toLowerCase()
  ](getServerUrl(), reqParams)
  if (success) {
    myOptions.value = data?.map(item => {
      return {
        label: item[props.keyName],
        value: item[props.valueName]
      }
    })
  } else {
    ElMessage.error(retInfo)
  }
}

onMounted(() => {
  getOptions()
})
</script>
